package com.example.function.integration.config;

import com.alibaba.fastjson2.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Map;
import java.util.Properties;

import static com.example.function.integration.constant.CommonConstant.*;

/**
 * @author fengcheng
 * @version 1.0
 * @date 2024-09-30
 */
@SuppressWarnings("ALL")
@Component
public class EmailConfig {

    @Resource
    private CommonResourceConfig commonResourceConfig;

    public static Logger logger = LoggerFactory.getLogger(EmailConfig.class);

    /**
     * 初始化邮件配置对象的函数，该函数返回一个MimeMessage实例对象，用于创建并发送邮件。
     *
     * @return
     */
    @PostConstruct
    public MimeMessage getMimeMessage() {
        logger.info("开始初始化邮件配置对象...");
        try {
            String emailUserName = commonResourceConfig.getEmailUserName();
            Properties props = new Properties();
            // 设置邮件服务器
            props.put(EMAIL_HOST, commonResourceConfig.getEmailHost());
            props.put(EMAIL_SMTP_AUTH, commonResourceConfig.getEmailSmtpAuth());
            props.put(EMAIL_SMTP_STARTTLS_ENABLE, commonResourceConfig.getEmailSmtpStarttlsEnable());
            // 根据配置创建Session实例
            Session session = Session.getInstance(props,
                    new Authenticator() {
                        protected PasswordAuthentication getPasswordAuthentication() {
                            return new PasswordAuthentication(emailUserName, commonResourceConfig.getEmailPassword());
                        }
                    });
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(emailUserName));
            logger.info("初始化邮件配置对象结束...");
            return message;
        } catch (MessagingException e) {
            logger.error(("初始化邮件配置对象时发生错误: " + e.getMessage() + "\n配置信息: \n邮件服务器: " + commonResourceConfig.getEmailHost()));
            throw new RuntimeException(e);
        }
    }

    /**
     * 发送邮件的函数，传入MimeMessage实例和消息内容信息的Map对象来创建并发送邮件。
     *
     * @param message
     * @param messageInfo
     */
    public void sendEmail(MimeMessage message, Map<String, String> messageInfo) {
        logger.info("开始发送邮件,邮件信息: " + JSONObject.toJSONString(messageInfo) + "\n...发送中...");
        try {
            // 收件人邮箱地址
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(messageInfo.get(RECEIVER_EMAIL)));
            // 设置邮件主题
            message.setSubject(messageInfo.get(EMAIL_SUBJECT));
            // 设置邮件正文
            message.setText(messageInfo.get(EMAIL_CONTENT));
            // 发送邮件
            Transport.send(message);
            logger.info("邮件发送成功!");
        } catch (MessagingException e) {
            logger.error(("发送邮件时发生错误: " + e.getMessage()));
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        // 发送邮件的SMTP服务器地址
        final String host = "pop.163.com";
        // 发送邮件的用户名和密码
        final String username = "qdaicheng@163.com";
        final String password = "ENGMTBBFKFGJPUOO";

        Properties props = new Properties();
        // 设置邮件服务器
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");

        // 根据配置创建Session实例
        Session session = Session.getInstance(props,
                new Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);
                    }
                });
        try {
            // 创建MimeMessage实例
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(username));
            // 收件人邮箱地址
            message.addRecipient(Message.RecipientType.TO, new InternetAddress("qdaicheng@163.com"));
            // 设置邮件主题
            message.setSubject("邮件主题");
            // 设置邮件正文
            message.setText("这是邮件的正文内容。");

            // 发送邮件
            Transport.send(message);

            System.out.println("邮件发送成功!");
        } catch (MessagingException e) {
            System.out.println("创建或发送邮件时发生错误: " + e.getMessage());
            throw new RuntimeException(e);
        }
    }
}
